package com.leyou.goods.service;

import com.leyou.goods.utils.ThreadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;

@Service
@Slf4j
public class GoodsHtmlService {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private TemplateEngine templateEngine;

    public void createHtml(Long spuId){

        // 创建输出流
        File file = new File("E:\\java-code\\springcloud\\item\\" + spuId + ".html");

        try (PrintWriter writer = new PrintWriter(file))
        {
            // 获取页面数据
            Map<String, Object> spuMap = this.goodsService.loadData(spuId);

            // 创建thymeleaf上下文对象
            Context context = new Context();
            // 把数据放入上下文对象
            context.setVariables(spuMap);

            // 执行页面静态化方法
            templateEngine.process("item", context, writer);

        }catch (Exception e){
            e.printStackTrace();
            log.error("页面静态化出错：{}，"+ e, spuId);
        }
    }

    /**
     * 新建线程处理页面静态化
     * @param spuId
     */
    public void asyncExecute(Long spuId) {
        ThreadUtils.execute(()->createHtml(spuId));
    }


    public void deleteHtml(Long id) {
        File file = new File("E:\\java-code\\springcloud\\item\\" + id + ".html");
        file.deleteOnExit();
    }
}
